﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using SohuWeb.Models;

namespace SohuWeb.Controllers {

    [HandleError]
    public class AccountController : Controller {

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext) {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }

        // **************************************
        // URL: /Account/LogOn
        // **************************************

        public ActionResult LogOn() {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl) {
            if (ModelState.IsValid) {
                User user = MembershipService.GetUser(model.UserName, model.Password);
                if (user != null) {
                    Session["user"] = user;
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    if (!String.IsNullOrEmpty(returnUrl)) {
                        return Redirect(returnUrl);
                    } else {
                        return RedirectToAction("CSVUpload", "Cms");
                    }
                } else {
                    ModelState.AddModelError("", "提供的用户名或密码不正确。");
                }
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            return View(model);
        }

        // **************************************
        // URL: /Account/LogOff
        // **************************************

        public ActionResult LogOff() {
            FormsService.SignOut();

            return RedirectToAction("LogOn", "Account");
        }

        // **************************************
        // URL: /Account/Register
        // **************************************

        //public ActionResult Register() {
        //    ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
        //    return View();
        //}

        //[HttpPost]
        //public ActionResult Register(RegisterModel model) {
        //    if (ModelState.IsValid) {
        //        // 尝试注册用户
        //        MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

        //        if (createStatus == MembershipCreateStatus.Success) {
        //            FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
        //            return RedirectToAction("Index", "Home");
        //        } else {
        //            ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
        //        }
        //    }

        //    // 如果我们进行到这一步时某个地方出错，则重新显示表单
        //    ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
        //    return View(model);
        //}

        // **************************************
        // URL: /Account/ChangePassword
        // **************************************

        [Authorize]
        public ActionResult ChangePassword() {
            ViewData["CurrentPage"] = "ChangePassword";
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model) {
            if (ModelState.IsValid) {
                if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword)) {
                    return RedirectToAction("ChangePasswordSuccess");
                } else {
                    ModelState.AddModelError("", "当前密码不正确或新密码无效。");
                }
            }

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        // **************************************
        // URL: /Account/ChangePasswordSuccess
        // **************************************

        public ActionResult ChangePasswordSuccess() {
            return View();
        }

        [Authorize]
        public ActionResult UserList() {
            //ViewData["TableHeader"] = "用户编号,用户名称,登录密码,操作权限,备注,操作";
            DBUtil util = new DBUtil();
            ViewData["UserList"] = util.GetAllUser();
            return View();
        }

        [Authorize]
        public ActionResult NewUser() {
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View();
        }

        [HttpPost]
        public ActionResult NewUser(NewUserModel model) {
            if (String.IsNullOrEmpty(model.UserName)) throw new ArgumentException("值不能为 null 或为空。", "userName");
            if (String.IsNullOrEmpty(model.Password)) throw new ArgumentException("值不能为 null 或为空。", "password");

            
            DBUtil util = new DBUtil();
            if (util.CreateUser(model.UserName, model.Password, model.Memo, model.Level)) {
                return RedirectToAction("CreateUserSuccess", new { @user = model.UserName });
            }
            //if (ModelState.IsValid) {
            //    // 尝试注册用户
            //    MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

            //    if (createStatus == MembershipCreateStatus.Success) {
            //        FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
            //        return RedirectToAction("Index", "Home");
            //    } else {
            //        ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
            //    }
            //}

            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return View(model);
        }

        public ActionResult CreateUserSuccess(string user) {
            ViewData["UserName"] = user;
            return View();
        }
    }
}
